package com.pjedu.nbmallwebsitesystem.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjedu.nbmallcommon.common.Constants;
import com.pjedu.nbmallcommon.common.ServiceResultEnum;
import com.pjedu.nbmallcommon.utils.Result;
import com.pjedu.nbmallcommon.utils.ResultGenerator;
import com.pjedu.nbmalluser.mapper.MallUserMapper;
import com.pjedu.nbmalluser.vo.MallUserVO;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * six-mall系统身份验证拦截器
 *这里是类的注释*/
@Component
public class LoginFilter implements Filter {

    private MallUserMapper mallUserMapper;

    public MallUserMapper getMallUserMapper() {
        return mallUserMapper;
    }

    public void setMallUserMapper(MallUserMapper mallUserMapper) {
        this.mallUserMapper = mallUserMapper;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //判断session中是否存储着用户数据
        if (null == request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY)) {
            String ajaxHeader = request.getHeader("X-Requested-With");// ajax请求特有的请求头
            //判断是否是ajax请求
            if ("XMLHttpRequest".equals(ajaxHeader)) {
                Result result = ResultGenerator.genFailResult(ServiceResultEnum.NEED_LOGIN.getResult());
                try {
                    response.setContentType("application/json");
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().print(new ObjectMapper().writeValueAsString(result));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/login");
            }
            return;
        }
        // 把当前登录的用户信息，塞到request对象里面
        MallUserVO mallUserVO = (MallUserVO) request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY);
        //重写了HttpServletRequest的子类ParameterRequestWrapper,这样我们就可以在拦截器里把数据添加到request中
        ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper(request);
        parameterRequestWrapper.addParameter(Constants.LOGIN_USER_USER_ID, new String[]{mallUserVO.getUserId().toString()});
        filterChain.doFilter(parameterRequestWrapper, servletResponse);
    }
}
